//
//  OldPhotoUploadController.m
//  OldPhoto
//
//  Created by 蓝鳍互娱 on 2024/7/29.
//

#import "OldPhotoUploadController.h"
#import "OldPhotoCardView.h"
#import "OldPhotoUploadCollectionCell.h"
#import <Photos/Photos.h>
#import "AppDelegate.h"
#import "TZImagePickerController.h"
#import "OldPhotoAddAlertView.h"
@interface OldPhotoUploadController ()<UICollectionViewDelegate,UICollectionViewDataSource,TZImagePickerControllerDelegate>
@property (nonatomic, strong)OldPhotoCardView * oldPhotoCardView;
@property (nonatomic, strong)UICollectionView * oldPhotoUploadCollectionView;
@property (nonatomic, strong) NSMutableArray *oldPhotoCards;
@property (nonatomic, assign) NSInteger selectIndexPath;
@end

@implementation OldPhotoUploadController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = OldPhotoHex(@"#FFFFFF");
    [self creatOldPhotoNavView];
    self.oldPhotoNavTitle = @"最值得留恋的拍照瞬间";
    [self initOldPhoto];
    [self updataOldPhoto];
}
- (void)creatOldPhotoInitView{
    [super creatOldPhotoInitView];
    
    self.oldPhotoCardView = [[OldPhotoCardView alloc] init];
    [self.view addSubview:self.oldPhotoCardView];
    [self.oldPhotoCardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(OldPhotoRatio(0)));
        make.right.equalTo(@(OldPhotoRatio(0)));
        make.top.equalTo(@(OldPhotoRatio(112)+OldPhotoTopSafeHeight));
        make.height.equalTo(@(OldPhotoRatio(106)));
    }];
    OldPhotoWeakSelf
    self.oldPhotoCardView.OldPhotoCardAddBlock = ^{
        [OldPhotoAddAlertView showOldPhotoAddAlertView:^(NSString * _Nonnull name, BOOL isFort) {
            if (isFort) {
                NSMutableDictionary *oldPhotoCardDic = [[NSMutableDictionary alloc] init];
                [oldPhotoCardDic setObject:name forKey:@"name"];
                [oldPhotoCardDic setObject:@"" forKey:@"index"];
                [oldPhotoCardDic setObject:@"" forKey:@"img"];
                [weakSelf.oldPhotoCards insertObject:oldPhotoCardDic atIndex:0];
            }else{
                NSMutableDictionary *oldPhotoCardDic = [[NSMutableDictionary alloc] init];
                [oldPhotoCardDic setObject:name forKey:@"name"];
                [oldPhotoCardDic setObject:@"" forKey:@"index"];
                [oldPhotoCardDic setObject:@"" forKey:@"img"];
                [weakSelf.oldPhotoCards addObject:oldPhotoCardDic];
            }
            [[NSUserDefaults standardUserDefaults] setObject:weakSelf.oldPhotoCards.copy forKey:@"OldPhotoCard"];
            [weakSelf.oldPhotoUploadCollectionView reloadData];
            [weakSelf updataOldPhoto];
        }];
    };
    
    UICollectionViewFlowLayout* oldPhotoUploadFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    oldPhotoUploadFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    oldPhotoUploadFlowLayout.sectionInset = UIEdgeInsetsMake(OldPhotoRatio(0), OldPhotoRatio(24),OldPhotoRatio(0),OldPhotoRatio(24));
    self.oldPhotoUploadCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:oldPhotoUploadFlowLayout];
    self.oldPhotoUploadCollectionView.backgroundColor = [UIColor clearColor];
    self.oldPhotoUploadCollectionView.dataSource = self;
    self.oldPhotoUploadCollectionView.delegate = self;
    [self.oldPhotoUploadCollectionView registerClass:[OldPhotoUploadCollectionCell class] forCellWithReuseIdentifier:@"OldPhotoUploadCollectionCell"];
    [self.view addSubview:self.oldPhotoUploadCollectionView];
    [self.oldPhotoUploadCollectionView  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(OldPhotoRatio(0)));
        make.right.equalTo(@(OldPhotoRatio(0)));
        make.top.equalTo(self.oldPhotoCardView.mas_bottom).offset(OldPhotoRatio(38));
        make.bottom.equalTo(@(OldPhotoRatio(0)));
    }];
}
- (void)initOldPhoto{
    self.oldPhotoCards = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"OldPhotoCard"]];
    if (!self.oldPhotoCards.count) {
        self.oldPhotoCards = [[NSMutableArray alloc] init];
        for (int i = 0; i < 28; i++) {
            NSMutableDictionary *oldPhotoCardDic = [[NSMutableDictionary alloc] init];
            [oldPhotoCardDic setObject:@"" forKey:@"name"];
            [oldPhotoCardDic setObject:[NSString stringWithFormat:@"%d",i+1] forKey:@"index"];
            [oldPhotoCardDic setObject:@"" forKey:@"img"];
            [self.oldPhotoCards addObject:oldPhotoCardDic];
        }
    }
}
- (void)updataOldPhoto{
    int oldPhotoNum = 0;
    for (NSDictionary *oldPhotoCardDic in self.oldPhotoCards) {
        NSString * img =  [oldPhotoCardDic objectForKey:@"img"];
        if (img.length > 0) {
            oldPhotoNum = oldPhotoNum + 1;
        }
    }
    self.oldPhotoCardView.oldPhotoCardAllNum = [NSString stringWithFormat:@"%zd",self.oldPhotoCards.count];
    self.oldPhotoCardView.oldPhotoCardNum = [NSString stringWithFormat:@"%d",oldPhotoNum];
}
//相册权限
- (void)requestPhotoAuthorization:(void(^)(BOOL phpAvailable))callback{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusAuthorized) {
        // 已授权
        callback(true);
    }else if (status == PHAuthorizationStatusNotDetermined) {
        // 未决定
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                callback(true);
            } else {
                
            }
        }];
    } else{
        // 拒绝访问
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你的相册权限未授权，我们需要得到您相册的权限来上传照片" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            // 取消
            callback(false);
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 去设置
            NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                [[UIApplication sharedApplication] openURL:settingURL options:@{} completionHandler:^(BOOL success) {
                    // 成功进入设置
                }];
            }
        }]];
        [((AppDelegate*)[[UIApplication sharedApplication] delegate]).window.rootViewController presentViewController:alert animated:YES completion:nil];
    }
}
#pragma mark - UICollectionViewDelegateFlowLayout method
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.oldPhotoCards.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat itemW = (OldPhotoScreenWidth - OldPhotoRatio(72))/2;
    return CGSizeMake(itemW, itemW/340 * 454);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return OldPhotoRatio(24);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return OldPhotoRatio(24);
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    OldPhotoUploadCollectionCell *oldPhotoUploadCollectionCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"OldPhotoUploadCollectionCell" forIndexPath:indexPath];
    oldPhotoUploadCollectionCell.oldPhotoUploadDic = self.oldPhotoCards[indexPath.row];
    return oldPhotoUploadCollectionCell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.selectIndexPath = indexPath.row;
    OldPhotoWeakSelf
    [self requestPhotoAuthorization:^(BOOL phpAvailable) {
        if(phpAvailable){
            dispatch_async(dispatch_get_main_queue(), ^{
                TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:weakSelf];
                imagePickerController.showSelectBtn = NO;
                imagePickerController.allowCrop = NO;
                CGRect frame = weakSelf.view.frame;
                imagePickerController.cropRect = frame;
                imagePickerController.allowPickingGif = NO;
                imagePickerController.allowPickingVideo = NO;
                imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
                [((AppDelegate*)([UIApplication sharedApplication].delegate)).window.rootViewController presentViewController:imagePickerController animated:YES completion:^{
                    
                }];
            });
        }
    }];
}
#pragma mark -- TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    UIImage * oldPhotoImg = photos[0];
    NSString *olPhotoStr = [UIImagePNGRepresentation(oldPhotoImg) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSMutableDictionary *oldPhotoCardDic = [NSMutableDictionary dictionaryWithDictionary:self.oldPhotoCards[self.selectIndexPath]];
    [oldPhotoCardDic setObject:olPhotoStr forKey:@"img"];
    [self.oldPhotoCards replaceObjectAtIndex:self.selectIndexPath withObject:oldPhotoCardDic];
    
    [[NSUserDefaults standardUserDefaults] setObject:self.oldPhotoCards.copy forKey:@"OldPhotoCard"];
    [self updataOldPhoto];
    [self.oldPhotoUploadCollectionView reloadData];
}
@end
